package com.cf.game.im.handler;

import cn.hutool.http.HtmlUtil;
import com.cf.constant.EnumReturnCode;
import com.cf.game.im.dao.ChatMapper;
import com.cf.game.im.model.ChatMsg;
import com.cf.game.msg.AckResponse;
import com.cf.game.msg.ChatMessageRequest;
import com.cf.game.msg.ChatMessageResponse;
import com.cf.game.msg.Response;
import com.cf.game.node.NodeService;
import com.cf.id.SnowflakeId;
import com.cf.user.login.service.UserInfoService;
import com.cf.util.NumberUtil;
import com.cf.util.ObjectJsonUtil;
import io.vertx.core.eventbus.EventBus;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;

/**
 * boot-game-AbsHandler
 *
 * @author <a href="2428922347@qq.com">Zhu mingming</a>
 * @info
 * @since 2018/8/1 上午 11:47
 */
public class AbsHandler {

    @Autowired
    protected SnowflakeId id;

    @Autowired
    protected ChatMapper chatMapper;

    @Autowired
    protected NodeService nodeService;

    @Autowired
    protected UserInfoService userInfoService;

    protected ChatMsg saveChatMessage(ChatMessageRequest chatMsg) {
        ChatMsg msg = new ChatMsg();
        msg.setMessageType(chatMsg.getMsgType());
        msg.setChatTime(new Date());
        msg.setContent(HtmlUtil.removeHtmlTag(chatMsg.getContent()));
        msg.setReceive(chatMsg.getReceiver());
        msg.setSender(chatMsg.getSender());
        msg.setUinId(chatMsg.getUinId());
        msg.setId(id.nextId());
        msg.setExtra(ObjectJsonUtil.toString(chatMsg.getExtra()));
        this.chatMapper.insert(msg);
        return msg;
    }


    protected void deliveryMsg(long receiverId, EventBus ebs, ChatMsg cMsg, String type) {
        String receiveNode = nodeService.getUserNode(receiverId);
        if (!StringUtils.isEmpty(receiveNode)) {
            ChatMessageResponse chatMessageResponse = new ChatMessageResponse();
            BeanUtils.copyProperties(cMsg, chatMessageResponse);
            if (NumberUtil.isDigit(chatMessageResponse.getSender() + "")) {
                chatMessageResponse.setSendInfo(userInfoService.getUserInfo(chatMessageResponse.getSender() + ""));
            }
            chatMessageResponse.setType(type);
            ebs.publish(receiveNode, ObjectJsonUtil.toString(Response.instance(receiverId, EnumReturnCode.SUCCESS.getCode(), ObjectJsonUtil.toString(chatMessageResponse))));
        }
    }


    protected void sendStepAck(long senderId, String uinId, EventBus ebs) {
        String sendNode = nodeService.getUserNode(senderId);
        if (!StringUtils.isEmpty(sendNode)) {
            AckResponse ackResponse = new AckResponse(uinId);
            ebs.publish(sendNode, ObjectJsonUtil.toString(Response.instance(senderId, EnumReturnCode.SUCCESS.getCode(), ObjectJsonUtil.toString(ackResponse))));
        }
    }


}
